<template>
  <view class="production-plan-container">
    <!-- 顶部导航栏 -->
    <cu-custom bgColor="bg-blue" :isBack="true">
      <view slot="content" class="nav-title">生产计划</view>
      <view slot="right" class="nav-right" @click="openFilterModal">
        <text class="cuIcon-filter text-white"></text>
        <text class="filter-text">筛选</text>
      </view>
    </cu-custom>

    <!-- 筛选栏 -->
    <view class="filter-bar bg-white padding-sm">
      <scroll-view scroll-x class="nav">
        <view class="flex text-center">
          <view
            v-for="(item, index) in statusFilters"
            :key="index"
            class="cu-item flex-sub"
            :class="item.statusClass"
            @tap="changeStatusFilter(item.value)"
          >
            <text>{{ item.text }}</text>
            <text class="badge" v-if="item.count > 0">{{ item.count }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 计划列表 -->
    <scroll-view
      scroll-y
      class="plan-list"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="planList.length > 0">
        <view
          v-for="plan in filteredPlans"
          :key="plan.id"
          class="plan-item bg-white margin-sm radius padding"
          @tap="goToDetail(plan.id)"
        >
          <!-- 计划头部信息 -->
          <view class="flex justify-between align-center margin-bottom-sm">
            <view class="flex align-center">
              <text class="text-lg text-bold">{{ plan.planName }}</text>
              <view class="cu-tag sm" :class="plan.statusClass">
                {{ plan.statusText }}
              </view>
            </view>
            <text class="text-gray text-sm">{{ plan.createTime }}</text>
          </view>

          <!-- 订单信息 -->
          <view class="flex align-center margin-bottom-sm">
            <text class="cuIcon-goods text-blue margin-right-xs"></text>
            <text class="text-sm text-gray">订单编号：{{ plan.orderNo }}</text>
          </view>


          <!-- 任务统计 -->
          <view class="task-stats flex justify-between">
            <view class="stat-item text-center">
              <text class="text-lg text-bold text-blue">{{
                plan.totalTasks || 0
              }}</text>
              <text class="text-xs text-gray">总任务</text>
            </view>
            <view class="stat-item text-center">
              <text class="text-lg text-bold text-orange">{{
                plan.pendingTasks || 0
              }}</text>
              <text class="text-xs text-gray">待处理</text>
            </view>
            <view class="stat-item text-center">
              <text class="text-lg text-bold text-green">{{
                plan.completedTasks || 0
              }}</text>
              <text class="text-xs text-gray">已完成</text>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view
            class="action-buttons flex justify-end margin-top-sm"
            @tap.stop=""
          >
            <button class="cu-btn sm line-blue" @tap="goToTasks(plan.id)">
              查看任务
            </button>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else-if="!loading" class="empty-state text-center padding-xl">
        <text class="cuIcon-goods text-gray text-xxl"></text>
        <text class="text-gray margin-top">暂无生产计划</text>
        <text class="text-sm text-gray margin-top"
          >请联系管理员创建生产计划</text
        >
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore" class="text-center padding">
        <text class="text-gray">加载更多...</text>
      </view>
    </scroll-view>

    <!-- 筛选弹窗 -->
    <view
      class="filter-modal"
      v-if="showFilterModal"
      @click="showFilterModal = false"
    >
      <view class="filter-content" @click.stop>
        <view class="filter-header">
          <text class="filter-title">筛选条件</text>
          <text class="close-btn" @click="showFilterModal = false">×</text>
        </view>
        <view class="filter-body">
          <!-- 查询条件 -->
          <view class="filter-group">
            <text class="group-title">查询条件</text>
            <view class="input-group">
              <view class="input-item">
                <text class="input-label">计划名称</text>
                <input
                  class="filter-input"
                  type="text"
                  placeholder="请输入计划名称"
                  v-model="filterForm.planName"
                />
              </view>
              <view class="input-item">
                <text class="input-label">订单号</text>
                <input
                  class="filter-input"
                  type="text"
                  placeholder="请输入订单号"
                  v-model="filterForm.orderNo"
                />
              </view>
            </view>
          </view>

          <!-- 状态筛选 -->
          <view class="filter-group">
            <text class="group-title">计划状态</text>
            <view class="checkbox-group">
              <view
                v-for="status in statusOptions"
                :key="status.value"
                class="checkbox-item"
                :class="{ checked: selectedStatuses.includes(status.value) }"
                @click="toggleStatus(status.value)"
              >
                <text class="checkbox-text">{{ status.text }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="filter-footer">
          <view class="filter-btn reset" @click="resetFilter">重置</view>
          <view class="filter-btn confirm" @click="applyFilter">确定</view>
        </view>
      </view>
    </view>

    <!-- 搜索模态框 -->
    <view v-if="showSearchModal" class="cu-modal show">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end">
          <view class="content">搜索计划</view>
          <view class="action">
            <text
              class="cuIcon-close text-red"
              @tap="showSearchModal = false"
            ></text>
          </view>
        </view>
        <view class="padding">
          <view class="cu-form-group">
            <view class="title">计划名称</view>
            <input v-model="searchForm.planName" placeholder="请输入计划名称" />
          </view>
          <view class="cu-form-group">
            <view class="title">订单编号</view>
            <input v-model="searchForm.orderNo" placeholder="请输入订单编号" />
          </view>
          <view class="cu-form-group">
            <view class="title">状态</view>
            <picker
              :value="searchForm.statusIndex"
              :range="statusOptions"
              range-key="text"
              @change="onStatusChange"
            >
              <view class="picker">
                {{
                  searchForm.statusIndex >= 0
                    ? statusOptions[searchForm.statusIndex].text
                    : "请选择状态"
                }}
              </view>
            </picker>
          </view>
          <view class="flex justify-between margin-top">
            <button
              class="cu-btn bg-gray flex-sub margin-right-sm"
              @tap="resetSearch"
            >
              重置
            </button>
            <button class="cu-btn bg-blue flex-sub" @tap="doSearch">
              搜索
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { productionPlan } from "@/api/mes/productionPlan.js";

export default {
  data() {
    return {
      planList: [],
      loading: false,
      refreshing: false,
      hasMore: true,
      currentPage: 1,
      pageSize: 10,
      currentStatus: "",

      // 状态筛选
      statusFilters: [
        { text: "全部", value: "", statusClass: "text-blue cur", count: 0 },
        { text: "已下发", value: "2", statusClass: "", count: 0 },
        { text: "进行中", value: "4", statusClass: "", count: 0 },
        { text: "已完成", value: "5", statusClass: "", count: 0 },
      ],

      // 状态选项
      statusOptions: [
        { text: "全部", value: "" },
        { text: "已下发", value: "2" },
        { text: "进行中", value: "4" },
        { text: "已完成", value: "5" },
      ],

      // 模态框控制
      showSearchModal: false,

      // 搜索表单
      searchForm: {
        planName: "",
        orderNo: "",
        status: "",
        statusIndex: -1,
      },
      showFilterModal: false,
      selectedStatuses: [],
      filterForm: {
        planName: "",
        orderNo: "",
      },
    };
  },

  onLoad() {
    this.loadPlanList();
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshPlanList();
  },

  computed: {
    // 过滤后的计划列表
    filteredPlans() {
      return this.planList;
    },
  },

  methods: {
    // 加载计划列表
    async loadPlanList(isRefresh = false) {
      if (this.loading) return;

      this.loading = true;
      if (isRefresh) {
        this.currentPage = 1;
        this.hasMore = true;
      }

      try {
        const params = {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          status: this.currentStatus,
        };

        // 添加模糊查询参数，根据QueryGenerator规则添加*前后缀触发LIKE查询
        if (this.searchForm.planName && this.searchForm.planName.trim()) {
          params.planName = '*' + this.searchForm.planName.trim() + '*';
        }
        if (this.searchForm.orderNo && this.searchForm.orderNo.trim()) {
          params.orderNo = '*' + this.searchForm.orderNo.trim() + '*';
        }

        const response = await productionPlan.list(params);

        // 根据实际API响应结构提取数据
        const newData = response.data?.result.records || [];

        // 数据预处理
        const processedData = newData.map((item) => {
          const processed = {
            ...item,
            statusClass: this.calculateStatusClass(item),
            statusText: this.calculateStatusText(item),
            createTime: this.formatDate(item.createTime),
          };
          return processed;
        });

        if (isRefresh) {
          this.planList = processedData;
        } else {
          this.planList = [...this.planList, ...processedData];
        }

        this.hasMore =
          this.currentPage <
          Math.ceil((response.result?.total || 0) / this.pageSize);
        this.currentPage++;

        // 更新状态统计
        this.updateStatusCount(response.result?.statusCount || {});
      } catch (error) {
        console.error("加载计划列表失败:", error);
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
        this.refreshing = false;
      }
    },

    // 刷新列表
    refreshPlanList() {
      this.loadPlanList(true);
    },

    // 下拉刷新
    onRefresh() {
      this.refreshing = true;
      this.refreshPlanList();
    },

    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.loadPlanList();
      }
    },

    // 切换状态筛选
    changeStatusFilter(status) {
      this.currentStatus = status;
      this.statusFilters.forEach((item) => {
        item.statusClass = item.value === status ? "text-blue cur" : "";
      });
      this.refreshPlanList();
    },

    // 计算状态样式类
    calculateStatusClass(item) {
      const status = item.status;
      const statusMap = {
        // 数字状态码映射
        1: "bg-gray", // 草稿
        2: "bg-blue", // 已下发
        3: "bg-orange", // 已领取
        4: "bg-cyan", // 进行中
        5: "bg-yellow", // 已暂停
        6: "bg-green", // 已完成
        // 字符串状态映射（兼容）
        DRAFT: "bg-gray",
        ISSUED: "bg-blue",
        CLAIMED: "bg-orange",
        IN_PROGRESS: "bg-cyan",
        PAUSED: "bg-yellow",
        COMPLETED: "bg-green",
      };
      return statusMap[status] || "bg-gray";
    },

    // 计算状态文本
    calculateStatusText(item) {
      const status = item.status;
      const statusMap = {
        // 数字状态码映射
        1: "草稿",
        2: "已下发",
        3: "已领取",
        4: "进行中",
        5: "已暂停",
        6: "已完成",
        // 字符串状态映射（兼容）
        DRAFT: "草稿",
        ISSUED: "已下发",
        CLAIMED: "已领取",
        IN_PROGRESS: "进行中",
        PAUSED: "已暂停",
        COMPLETED: "已完成",
      };
      return statusMap[status] || "未知";
    },

    // 计算进度颜色类（用于数据预处理）
    calculateProgressColorClass(progress) {
      if (progress >= 100) return "text-green";
      if (progress >= 80) return "text-blue";
      if (progress >= 50) return "text-orange";
      return "text-red";
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return "";
      const date = new Date(dateStr);
      return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date
        .getMinutes()
        .toString()
        .padStart(2, "0")}`;
    },

    // 更新状态统计
    updateStatusCount(statusCount) {
      this.statusFilters.forEach((filter) => {
        filter.count = statusCount[filter.value] || 0;
      });
    },

    // 启动计划
    async startPlan(planId) {
      try {
        await productionPlan.start(planId);
        uni.showToast({
          title: "启动成功",
          icon: "success",
        });
        this.refreshPlanList();
      } catch (error) {
        console.error("启动计划失败:", error);
        uni.showToast({
          title: "启动失败",
          icon: "none",
        });
      }
    },

    // 暂停计划
    async pausePlan(planId) {
      try {
        await productionPlan.pause(planId);
        uni.showToast({
          title: "暂停成功",
          icon: "success",
        });
        this.refreshPlanList();
      } catch (error) {
        console.error("暂停计划失败:", error);
        uni.showToast({
          title: "暂停失败",
          icon: "none",
        });
      }
    },

    // 恢复计划
    async resumePlan(planId) {
      try {
        await productionPlan.start(planId);
        uni.showToast({
          title: "恢复成功",
          icon: "success",
        });
        this.refreshPlanList();
      } catch (error) {
        console.error("恢复计划失败:", error);
        uni.showToast({
          title: "恢复失败",
          icon: "none",
        });
      }
    },

    // 跳转到详情页
    goToDetail(planId) {
      uni.navigateTo({
        url: `/pages/production/plan/detail?id=${planId}`,
      });
    },

    // 跳转到任务页
    goToTasks(planId) {
      uni.navigateTo({
        url: `/pages/production/task/list?planId=${planId}`,
      });
    },

    // 状态选择器变化
    onStatusChange(e) {
      this.searchForm.statusIndex = e.detail.value;
      this.searchForm.status = this.statusOptions[e.detail.value].value;
    },

    // 执行搜索
    doSearch() {
      this.showSearchModal = false;
      this.refreshPlanList();
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        planName: "",
        orderNo: "",
        status: "",
        statusIndex: -1,
      };
      this.currentStatus = "";
      this.changeStatusFilter("");
    },

    // 打开筛选模态框
    openFilterModal() {
      this.showFilterModal = true;
    },

    // 切换状态选择
    toggleStatus(statusValue) {
      const index = this.selectedStatuses.indexOf(statusValue);
      if (index > -1) {
        this.selectedStatuses.splice(index, 1);
      } else {
        this.selectedStatuses.push(statusValue);
      }
    },

    // 重置筛选条件
    resetFilter() {
      this.filterForm = {
        planName: "",
        orderNo: "",
      };
      this.selectedStatuses = [];
    },

    // 应用筛选条件
    applyFilter() {
      // 将筛选条件同步到搜索表单
      this.searchForm.planName = this.filterForm.planName;
      this.searchForm.orderNo = this.filterForm.orderNo;
      
      // 如果选择了状态，使用第一个选中的状态
      if (this.selectedStatuses.length > 0) {
        this.currentStatus = this.selectedStatuses[0];
        // 更新状态筛选按钮样式
        this.statusFilters.forEach((item) => {
          item.statusClass = item.value === this.currentStatus ? "text-blue cur" : "";
        });
      }
      
      this.showFilterModal = false;
      this.refreshPlanList();
    },

    // 领取计划
    async claimPlan(planId) {
      try {
        await productionPlan.claim(planId);
        uni.showToast({
          title: "领取成功",
          icon: "success",
        });
        this.refreshPlanList();
      } catch (error) {
        console.error("领取计划失败:", error);
        uni.showToast({
          title: "领取失败",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style scoped>
.production-plan-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.filter-bar {
  border-bottom: 1px solid #eee;
}

.plan-list {
  height: calc(100vh - 200rpx);
}

.plan-item {
  border-left: 4px solid #007aff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.progress-bar {
  height: 8rpx;
  background-color: #f0f0f0;
  border-radius: 4rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 4rpx;
  transition: width 0.3s ease;
}

.progress-fill.text-green {
  background-color: #34c759;
}

.progress-fill.text-blue {
  background-color: #007aff;
}

.progress-fill.text-orange {
  background-color: #ff9500;
}

.progress-fill.text-red {
  background-color: #ff3b30;
}

.task-stats {
  border-top: 1px solid #f0f0f0;
  padding-top: 20rpx;
}

.stat-item {
  flex: 1;
}

.stat-item text:first-child {
  display: block;
}

.stat-item text:last-child {
  display: block;
  margin-top: 8rpx;
}

.action-buttons {
  border-top: 1px solid #f0f0f0;
  padding-top: 20rpx;
}

.create-options .option-item {
  padding: 40rpx;
  text-align: center;
  font-size: 32rpx;
}

.empty-state {
  margin-top: 200rpx;
}

.empty-state .cuIcon-goods {
  font-size: 120rpx;
  display: block;
  margin-bottom: 20rpx;
}

/* 筛选弹窗样式 */
.filter-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: flex-end;
}

.filter-content {
  width: 100%;
  background: white;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
  overflow: hidden;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 40rpx;
  border-bottom: 1px solid #f0f0f0;
}

.filter-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 48rpx;
  color: #999;
  line-height: 1;
}

.filter-body {
  padding: 40rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.filter-group {
  margin-bottom: 40rpx;
}

.group-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.input-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.input-label {
  width: 160rpx;
  font-size: 28rpx;
  color: #666;
  flex-shrink: 0;
}

.filter-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  padding: 0 20rpx;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.checkbox-item {
  padding: 16rpx 32rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 40rpx;
  background: #f8f8f8;
  transition: all 0.3s;
}

.checkbox-item.checked {
  border-color: #007aff;
  background: #e3f2fd;
}

.checkbox-text {
  font-size: 28rpx;
  color: #666;
}

.checkbox-item.checked .checkbox-text {
  color: #007aff;
}

.filter-footer {
  display: flex;
  padding: 30rpx 40rpx;
  border-top: 1px solid #f0f0f0;
  gap: 20rpx;
}

.filter-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 32rpx;
}

.filter-btn.reset {
  background: #f0f0f0;
  color: #666;
}

.filter-btn.confirm {
  background: #007aff;
  color: white;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.filter-text {
  font-size: 28rpx;
  color: white;
}
</style>
